package spiralOrder;

public class Solution {
    enum Direction {
        LEFT,
        RIGHT,
        UP,
        DOWN
    }
    public int[] spiralOrder(int[][] matrix) {
        Direction direction = Direction.RIGHT;
        int m = matrix.length;
        int n = matrix[0].length;
        int[] ans = new int[m*n];
        int index = 0;
        int left = 0,right = n-1,up = 0,down = m-1; // 矩阵的四条边
        while (index<ans.length) {
            switch (direction) {
                case UP -> {
                    for (int i = down; i >= up; i--) {
                        ans[index++] = matrix[i][left];
                    }
                    direction = Direction.RIGHT;
                    left++;
                } case DOWN -> {
                    for (int i = up; i <= down; i++) {
                        ans[index++] = matrix[i][right];
                    }
                    direction = Direction.LEFT;
                    right--;
                } case LEFT -> {
                    for (int j = right; j >= left; j--) {
                        ans[index++] = matrix[down][j];
                    }
                    direction = Direction.UP;
                    down--;
                } case RIGHT -> {
                    for (int j = left; j <= right; j++) {
                        ans[index++] = matrix[up][j];
                    }
                    direction = Direction.DOWN;
                    up++;
                }
            }
        }
        return ans;
    }
}
